﻿using DiffisionWithDecomposition;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DiffusionHistogram
{
    class Program
    {
        private static StreamWriter _streamWiter;
        private static long _writingInterval = 10000;

        static void Main(string[] args)
        {
            SimParameters.T_s = (long)1000 * 1000 * 1000 * 1000; // msec
            SimParameters.SimDuration = (long)1 * 1000 * 1000 * 1000;
            SimParameters.NumberOfMolecules = 10000; 
            SimParameters.MoleculeHalfLife = 16 * 1000 * 1000;
            SimParameters.DecompositionEnabled = false;
            SimParameters.StepSize = 0.00001;         //should be consistent with timetick
            SimParameters.TimeTick = 10000;
            SimParameters.ReportInterval = 1000000;
            SimParameters.MaxDistanceFromCellCenter = 1000000;
            SimParameters.XCoordinateOfCellPosition = 14;

            for (long i = 1024 * 1000 * 1000; i <= (long)1024 * 1000 * 1000; i = i * 2)
            {
                SimParameters.MoleculeHalfLife = i;
                PrintHistogramsToFile();
            }
        }

        public static void PrintHistogramsToFile()
        {
            var _streamWiter = new StreamWriter(String.Format("Logs\\NOABSZONE0 D={0}, N={1}, Dec={2}, HL={3}.txt, T_s={4}, Durat = {5}.txt, dT={6}, wrtInt={7}.txt", SimParameters.XCoordinateOfCellPosition,
                SimParameters.NumberOfMolecules, SimParameters.DecompositionEnabled, SimParameters.MoleculeHalfLife, SimParameters.T_s, SimParameters.SimDuration, SimParameters.StepSize, _writingInterval), false);

            Simulation.Instance.NewSimulationInstance();

            var capturedMoleculeCountList = new List<int>();

            var communication = new Communication();
            //communication._connectomeClient = _client;
            communication.SendOneBit(SimParameters.NumberOfMolecules, SimParameters.T_s);

            RecordStuff(communication, capturedMoleculeCountList);

            while (Simulation.Instance.EndCondition == false)
            {
                Simulation.Instance.DequeueEvent();
            }

            capturedMoleculeCountList.ForEach((x) => { _streamWiter.WriteLine(x); });
            _streamWiter.Flush();
            _streamWiter.Close();
        }

        private static void RecordStuff(Communication c, List<int> capturedMoleculeCountList)
        {
            capturedMoleculeCountList.Add(c.Cell.NumberOfAbsorbedMolecules);
            c.Cell.NumberOfAbsorbedMolecules = 0;

            Simulation.Instance.EnqueueEvent(
                new Event(Time.Instance.GetTimeAfterNanoSeconds(_writingInterval), () => RecordStuff(c, capturedMoleculeCountList)));
        }
    }
}
